// 欧冠8强球队数据
const teams = {
    // 左侧4支球队
    left: [
        { id: 'team1', name: '阿森纳', logo: 'images/Arsenal_FC.svg' },
        { id: 'team2', name: '皇马', logo: 'images/皇马.png' },
        { id: 'team3', name: '维拉', logo: 'images/Aston_Villa_logo.svg' },
        { id: 'team4', name: '巴黎', logo: 'images/Paris_Saint-Germain_F.C..svg' }
    ],
    // 右侧4支球队
    right: [
        { id: 'team5', name: '巴萨', logo: 'images/FC_Barcelona_(crest).png' },
        { id: 'team6', name: '多特', logo: 'images/Borussia_Dortmund_logo.svg' },
        { id: 'team7', name: '国米', logo: 'images/FC_Internazionale_Milano_2021.svg' },
        { id: 'team8', name: '拜仁', logo: 'images/FC_Bayern_München_logo_(2017).svg' },
    ]
};

// 赛事数据
const tournamentData = {
    teams: [
        // 预设队伍，用户可以修改或添加
    ],
    matches: [
        // 四分之一决赛
        {
            id: 'quarterfinal1', round: 'quarterfinal', position: 1,
            team1: { id: 'custom1', name: '队伍1', logo: '' },
            team2: { id: 'custom2', name: '队伍2', logo: '' },
            winner: null
        },
        {
            id: 'quarterfinal2', round: 'quarterfinal', position: 2,
            team1: { id: 'custom3', name: '队伍3', logo: '' },
            team2: { id: 'custom4', name: '队伍4', logo: '' },
            winner: null
        },
        {
            id: 'quarterfinal3', round: 'quarterfinal', position: 3,
            team1: { id: 'custom5', name: '队伍5', logo: '' },
            team2: { id: 'custom6', name: '队伍6', logo: '' },
            winner: null
        },
        {
            id: 'quarterfinal4', round: 'quarterfinal', position: 4,
            team1: { id: 'custom7', name: '队伍7', logo: '' },
            team2: { id: 'custom8', name: '队伍8', logo: '' },
            winner: null
        },
        
        // 半决赛
        {
            id: 'semifinal1', round: 'semifinal', position: 1,
            team1: { id: 'placeholder1', name: '待定', logo: '' },
            team2: { id: 'placeholder2', name: '待定', logo: '' },
            winner: null
        },
        {
            id: 'semifinal2', round: 'semifinal', position: 2,
            team1: { id: 'placeholder3', name: '待定', logo: '' },
            team2: { id: 'placeholder4', name: '待定', logo: '' },
            winner: null
        },
        
        // 决赛
        {
            id: 'final', round: 'final', position: 1,
            team1: { id: 'placeholder5', name: '待定', logo: '' },
            team2: { id: 'placeholder6', name: '待定', logo: '' },
            winner: null
        }
    ],
    champion: null
};

// 队伍颜色映射，用于生成文本logo
const teamColors = {
    '曼城': '#6CABDD',
    '皇马': '#FFFFFF',
    '拜仁': '#DC052D',
    '巴黎': '#004170',
    '巴萨': '#004D98',
    '多特': '#FDE100',
    '国米': '#0066B3',
    '阿森纳': '#EF0107',
    '维拉': '#95BFE5',
    '切尔西': '#034694',
    '利物浦': '#C8102E',
    '热刺': '#132257',
    '尤文': '#000000',
    '那不勒斯': '#12A0D7',
    '米兰': '#FB090B',
    '马竞': '#CB3524',
    '莱比锡': '#0A2240',
    '波尔图': '#005CA9',
    '比利亚雷亚尔': '#005187',
    '本菲卡': '#ED302D',
    // 默认颜色
    '默认': '#CCCCCC'
};

// 加载保存的预测数据
function loadPredictions() {
    try {
        const saved = localStorage.getItem('ucl-predictions');
        if (saved) {
            return JSON.parse(saved);
        }
    } catch (error) {
        console.error('加载预测数据失败:', error);
    }
    return null;
}

// 保存预测数据
function savePredictions(showAlert = false) {
    localStorage.setItem('ucl-predictions', JSON.stringify(tournamentData));
    if (showAlert) {
        // 使用更友好的方式显示保存成功消息
        console.log('预测已保存！');
        // 可以实现一个简单的提示区域显示保存成功
        showNotification('预测已保存！');
    }
}

// 显示通知消息
function showNotification(message, type = 'success') {
    // 如果已有通知，移除它
    const existingNotification = document.getElementById('notification');
    if (existingNotification) {
        document.body.removeChild(existingNotification);
    }
    
    // 创建新通知
    const notification = document.createElement('div');
    notification.id = 'notification';
    notification.className = `notification ${type}`;
    notification.textContent = message;
    
    document.body.appendChild(notification);
    
    // 3秒后自动消失
    setTimeout(() => {
        if (document.body.contains(notification)) {
            document.body.removeChild(notification);
        }
    }, 3000);
}

// 重置预测数据
function resetPredictions(showConfirm = true) {
    try {
        console.log('正在重置预测数据...');
        
        // 清除本地存储
        localStorage.removeItem('ucl-predictions');
        
        // 将teams数据重新加载到tournamentData.teams
        tournamentData.teams = [];
        // 合并左侧和右侧的球队
        const allTeams = [...teams.left, ...teams.right];
        // 添加到tournamentData
        allTeams.forEach(team => {
            tournamentData.teams.push({
                id: team.id,
                name: team.name,
                logo: team.logo
            });
        });
        
        // 重置四分之一决赛队伍和胜者
        const quarterFinals = tournamentData.matches.filter(m => m.round === 'quarterfinal');
        for (let i = 0; i < 4; i++) {
            if (i < 2) { // 左侧两场比赛
                quarterFinals[i].team1 = { 
                    id: teams.left[i*2].id, 
                    name: teams.left[i*2].name, 
                    logo: teams.left[i*2].logo 
                };
                quarterFinals[i].team2 = { 
                    id: teams.left[i*2+1].id, 
                    name: teams.left[i*2+1].name, 
                    logo: teams.left[i*2+1].logo 
                };
            } else { // 右侧两场比赛
                const rightIdx = i - 2;
                quarterFinals[i].team1 = { 
                    id: teams.right[rightIdx*2].id, 
                    name: teams.right[rightIdx*2].name, 
                    logo: teams.right[rightIdx*2].logo 
                };
                quarterFinals[i].team2 = { 
                    id: teams.right[rightIdx*2+1].id, 
                    name: teams.right[rightIdx*2+1].name, 
                    logo: teams.right[rightIdx*2+1].logo 
                };
            }
            quarterFinals[i].winner = null;
        }
        
        // 重置半决赛的队伍和胜者
        tournamentData.matches.forEach(match => {
            if (match.round === 'semifinal') {
                match.team1 = { id: `placeholder${match.position * 2 - 1}`, name: '待定', logo: '' };
                match.team2 = { id: `placeholder${match.position * 2}`, name: '待定', logo: '' };
                match.winner = null;
            }
            // 重置决赛的队伍和胜者
            else if (match.round === 'final') {
                match.team1 = { id: 'placeholder5', name: '待定', logo: '' };
                match.team2 = { id: 'placeholder6', name: '待定', logo: '' };
                match.winner = null;
            }
        });
        
        // 重置冠军
        tournamentData.champion = null;
        
        // 重新渲染
        renderTournament();
        
        if (showConfirm) {
            console.log('预测数据已重置');
            showNotification('预测数据已重置');
        }
    } catch (error) {
        console.error('重置预测数据时出错:', error);
    }
}

// 导出预测数据
function exportPredictions() {
    try {
        console.log('正在导出预测数据...');
        
        // 创建导出内容
        let exportContent = "欧冠预测结果\n\n";
        
        // 添加四分之一决赛结果
        exportContent += "四分之一决赛：\n";
        tournamentData.matches.filter(m => m.round === 'quarterfinal').forEach(match => {
            exportContent += `${match.team1.name} vs ${match.team2.name}: `;
            if (match.winner) {
                const winner = match.winner === match.team1.id ? match.team1.name : match.team2.name;
                exportContent += `${winner} 晋级\n`;
            } else {
                exportContent += "尚未选择\n";
            }
        });
        
        // 添加半决赛结果
        exportContent += "\n半决赛：\n";
        tournamentData.matches.filter(m => m.round === 'semifinal').forEach(match => {
            const team1Name = match.team1.name || '待定';
            const team2Name = match.team2.name || '待定';
            exportContent += `${team1Name} vs ${team2Name}: `;
            if (match.winner) {
                const winner = match.winner === match.team1.id ? match.team1.name : match.team2.name;
                exportContent += `${winner} 晋级\n`;
            } else {
                exportContent += "尚未选择\n";
            }
        });
        
        // 添加决赛结果
        exportContent += "\n决赛：\n";
        const finalMatch = tournamentData.matches.find(m => m.round === 'final');
        if (finalMatch) {
            const team1Name = finalMatch.team1.name || '待定';
            const team2Name = finalMatch.team2.name || '待定';
            exportContent += `${team1Name} vs ${team2Name}: `;
            if (finalMatch.winner) {
                const winner = finalMatch.winner === finalMatch.team1.id ? finalMatch.team1.name : finalMatch.team2.name;
                exportContent += `${winner} 获胜\n`;
            } else {
                exportContent += "尚未选择\n";
            }
        }
        
        // 添加冠军
        exportContent += "\n冠军：";
        if (tournamentData.champion) {
            exportContent += tournamentData.champion.name;
        } else {
            exportContent += "尚未决出";
        }
        
        // 创建并下载文件
        const blob = new Blob([exportContent], { type: 'text/plain' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `欧冠预测_${new Date().toISOString().slice(0, 10)}.txt`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        
        console.log('预测数据导出成功');
        showNotification('预测数据已导出');
    } catch (error) {
        console.error('导出预测数据时出错:', error);
    }
}

// 创建队伍卡片
function createTeamCard(team, isWinner = false) {
    const card = document.createElement('div');
    card.className = `team-card ${isWinner ? 'winner' : ''}`;
    card.dataset.teamId = team.id;
    
    const logoContainer = document.createElement('div');
    logoContainer.className = 'team-logo';
    
    // 优先使用SVG图标
    if (team.logo && team.logo.trim() !== '') {
        // 创建图片元素
        const img = document.createElement('img');
        img.src = team.logo;
        img.alt = team.name;
        img.style.maxWidth = '100%';
        img.style.maxHeight = '100%';
        
        // 图片加载失败时创建文本logo
        img.onerror = function() {
            console.log(`队伍 ${team.name} 的图标加载失败，使用文本替代`);
            logoContainer.innerHTML = '';
            logoContainer.appendChild(createTextLogo(team));
        };
        
        logoContainer.appendChild(img);
    } else {
        // 如果没有logo路径，使用文本logo
        logoContainer.appendChild(createTextLogo(team));
    }
    
    const nameElement = document.createElement('div');
    nameElement.className = 'team-name';
    nameElement.textContent = team.name;
    nameElement.contentEditable = true;
    nameElement.spellcheck = false;
    
    // 防止编辑团队名称时触发卡片点击事件
    nameElement.addEventListener('click', function(e) {
        e.stopPropagation();
    });
    
    // 编辑团队名称
    nameElement.addEventListener('blur', function() {
        const newName = this.textContent.trim();
        if (newName !== team.name && newName !== '') {
            team.name = newName;
            savePredictions(false);
            renderTournament();
        }
    });
    
    // 按下回车时完成编辑
    nameElement.addEventListener('keydown', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            this.blur();
        }
    });
    
    card.appendChild(logoContainer);
    card.appendChild(nameElement);
    
    return card;
}

// 创建文本logo（当图片加载失败时使用）
function createTextLogo(team) {
    const textLogo = document.createElement('div');
    textLogo.className = 'text-logo';
    
    // 查找队伍颜色，如果没有则使用默认颜色
    let teamName = team.name || '';
    let color = team.color || teamColors[teamName] || teamColors['默认'];
    
    // 为文本logo设置样式
    textLogo.style.backgroundColor = color;
    textLogo.style.color = isLightColor(color) ? '#000000' : '#FFFFFF';
    textLogo.style.width = '40px';
    textLogo.style.height = '40px';
    textLogo.style.display = 'flex';
    textLogo.style.alignItems = 'center';
    textLogo.style.justifyContent = 'center';
    textLogo.style.borderRadius = '50%';
    textLogo.style.fontWeight = 'bold';
    
    // 显示队伍名称的首字母或首个汉字
    textLogo.textContent = teamName.charAt(0);
    
    return textLogo;
}

// 判断颜色是否为浅色（用于决定文字颜色）
function isLightColor(color) {
    // 将颜色转换为RGB
    let r, g, b;
    
    if (color.startsWith('#')) {
        const hex = color.substring(1);
        r = parseInt(hex.substring(0, 2), 16);
        g = parseInt(hex.substring(2, 4), 16);
        b = parseInt(hex.substring(4, 6), 16);
    } else if (color.startsWith('rgb')) {
        const match = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/i);
        if (match) {
            r = parseInt(match[1]);
            g = parseInt(match[2]);
            b = parseInt(match[3]);
        } else {
            return false;
        }
    } else {
        return false;
    }
    
    // 计算亮度（采用YIQ公式）
    const brightness = (r * 299 + g * 587 + b * 114) / 1000;
    
    // 如果亮度大于128，则认为是浅色
    return brightness > 128;
}

// 更新比赛的队名，并添加更多调试信息
function updateTeamName(matchId, teamKey, newName) {
    console.log(`更新队名 - matchId: ${matchId}, teamKey: ${teamKey}, newName: ${newName}`);
    
    // 查找并更新对应比赛的队名
    let foundMatch = false;
    Object.keys(tournamentData).forEach(stage => {
        if (tournamentData[stage] && tournamentData[stage].matches) {
            tournamentData[stage].matches.forEach(match => {
                if (match && match.id === matchId && match[teamKey]) {
                    match[teamKey].name = newName;
                    foundMatch = true;
                    console.log(`已更新 ${stage} 阶段的队名`);
                }
            });
        }
    });
    
    if (!foundMatch) {
        console.error(`未找到匹配的比赛来更新队名: ${matchId}, ${teamKey}`);
    }
    
    // 更新半决赛队名
    updateNextRoundTeamName(matchId, teamKey, newName);
}

// 更新下一轮比赛的队名
function updateNextRoundTeamName(matchId, teamKey, newName) {
    console.log(`尝试更新下一轮队名 - matchId: ${matchId}, teamKey: ${teamKey}, newName: ${newName}`);
    
    // 8强到半决赛的队名更新
    if (matchId.startsWith('qf-left')) {
        // 安全检查
        if (!tournamentData.semifinalsLeft || !tournamentData.semifinalsLeft.matches || !tournamentData.semifinalsLeft.matches[0]) {
            console.error('找不到左侧半决赛数据');
            return;
        }
        
        const sfMatch = tournamentData.semifinalsLeft.matches[0];
        
        // 安全检查
        if (!tournamentData.quarterfinalsLeft || !tournamentData.quarterfinalsLeft.matches) {
            console.error('找不到左侧8强数据');
            return;
        }
        
        if (matchId === 'qf-left-1' && teamKey === 'team1') {
            if (tournamentData.quarterfinalsLeft.matches[0] && tournamentData.quarterfinalsLeft.matches[0].team1) {
                sfMatch.team1 = { 
                    name: newName, 
                    logo: tournamentData.quarterfinalsLeft.matches[0].team1.logo,
                    id: 'sf-left-1'
                };
                console.log('已更新左侧半决赛队伍1');
            }
        } else if (matchId === 'qf-left-1' && teamKey === 'team2') {
            if (tournamentData.quarterfinalsLeft.matches[0] && tournamentData.quarterfinalsLeft.matches[0].team2) {
                sfMatch.team1 = { 
                    name: newName, 
                    logo: tournamentData.quarterfinalsLeft.matches[0].team2.logo,
                    id: 'sf-left-1'
                };
                console.log('已更新左侧半决赛队伍1');
            }
        } else if (matchId === 'qf-left-2' && teamKey === 'team1') {
            if (tournamentData.quarterfinalsLeft.matches[1] && tournamentData.quarterfinalsLeft.matches[1].team1) {
                sfMatch.team2 = { 
                    name: newName, 
                    logo: tournamentData.quarterfinalsLeft.matches[1].team1.logo,
                    id: 'sf-left-2'
                };
                console.log('已更新左侧半决赛队伍2');
            }
        } else if (matchId === 'qf-left-2' && teamKey === 'team2') {
            if (tournamentData.quarterfinalsLeft.matches[1] && tournamentData.quarterfinalsLeft.matches[1].team2) {
                sfMatch.team2 = { 
                    name: newName, 
                    logo: tournamentData.quarterfinalsLeft.matches[1].team2.logo,
                    id: 'sf-left-2'
                };
                console.log('已更新左侧半决赛队伍2');
            }
        }
    } else if (matchId.startsWith('qf-right')) {
        // 安全检查
        if (!tournamentData.semifinalsRight || !tournamentData.semifinalsRight.matches || !tournamentData.semifinalsRight.matches[0]) {
            console.error('找不到右侧半决赛数据');
            return;
        }
        
        const sfMatch = tournamentData.semifinalsRight.matches[0];
        
        // 安全检查
        if (!tournamentData.quarterfinalsRight || !tournamentData.quarterfinalsRight.matches) {
            console.error('找不到右侧8强数据');
            return;
        }
        
        if (matchId === 'qf-right-1' && teamKey === 'team1') {
            if (tournamentData.quarterfinalsRight.matches[0] && tournamentData.quarterfinalsRight.matches[0].team1) {
                sfMatch.team1 = { 
                    name: newName, 
                    logo: tournamentData.quarterfinalsRight.matches[0].team1.logo,
                    id: 'sf-right-1'
                };
                console.log('已更新右侧半决赛队伍1');
            }
        } else if (matchId === 'qf-right-1' && teamKey === 'team2') {
            if (tournamentData.quarterfinalsRight.matches[0] && tournamentData.quarterfinalsRight.matches[0].team2) {
                sfMatch.team1 = { 
                    name: newName, 
                    logo: tournamentData.quarterfinalsRight.matches[0].team2.logo,
                    id: 'sf-right-1'
                };
                console.log('已更新右侧半决赛队伍1');
            }
        } else if (matchId === 'qf-right-2' && teamKey === 'team1') {
            if (tournamentData.quarterfinalsRight.matches[1] && tournamentData.quarterfinalsRight.matches[1].team1) {
                sfMatch.team2 = { 
                    name: newName, 
                    logo: tournamentData.quarterfinalsRight.matches[1].team1.logo,
                    id: 'sf-right-2'
                };
                console.log('已更新右侧半决赛队伍2');
            }
        } else if (matchId === 'qf-right-2' && teamKey === 'team2') {
            if (tournamentData.quarterfinalsRight.matches[1] && tournamentData.quarterfinalsRight.matches[1].team2) {
                sfMatch.team2 = { 
                    name: newName, 
                    logo: tournamentData.quarterfinalsRight.matches[1].team2.logo,
                    id: 'sf-right-2'
                };
                console.log('已更新右侧半决赛队伍2');
            }
        }
    }
    
    // 重新渲染半决赛
    try {
        renderMatches('semifinals-left', tournamentData.semifinalsLeft.matches);
        renderMatches('semifinals-right', tournamentData.semifinalsRight.matches);
        console.log('已重新渲染半决赛');
    } catch (error) {
        console.error('重新渲染半决赛时发生错误:', error);
    }
}

// 创建比赛元素
function createMatchElement(match) {
    const matchElement = document.createElement('div');
    matchElement.className = 'match';
    matchElement.dataset.matchId = match.id;
    
    // 添加两支球队
    const team1Card = createTeamCard(match.team1);
    team1Card.dataset.matchId = match.id;
    team1Card.dataset.teamKey = 'team1';
    
    const team2Card = createTeamCard(match.team2);
    team2Card.dataset.matchId = match.id;
    team2Card.dataset.teamKey = 'team2';
    
    // 如果有胜者，标记选中状态
    if (match.winner) {
        if (match.winner === match.team1.id) {
            team1Card.classList.add('selected');
        } else if (match.winner === match.team2.id) {
            team2Card.classList.add('selected');
        }
    }
    
    // 为每个队伍卡片添加点击事件
    team1Card.addEventListener('click', function() {
        console.log(`点击了队伍卡片: ${match.team1.name}, 比赛ID: ${match.id}`);
        selectWinner(match.id, match.team1.id);
    });
    
    team2Card.addEventListener('click', function() {
        console.log(`点击了队伍卡片: ${match.team2.name}, 比赛ID: ${match.id}`);
        selectWinner(match.id, match.team2.id);
    });
    
    // 添加VS标志
    const vsDiv = document.createElement('div');
    vsDiv.className = 'vs';
    vsDiv.textContent = 'VS';
    
    // 组装比赛元素
    matchElement.appendChild(team1Card);
    matchElement.appendChild(vsDiv);
    matchElement.appendChild(team2Card);
    
    return matchElement;
}

// 更新比分
function updateScore(matchId, teamKey, score) {
    // 查找并更新对应比赛的比分
    Object.keys(tournamentData).forEach(stage => {
        tournamentData[stage].matches.forEach(match => {
            if (match.id === matchId) {
                match[teamKey].score = score;
            }
        });
    });
}

// 选择胜者并晋级
function selectWinner(matchId, teamId) {
    console.log(`选择胜者: 比赛ID ${matchId}, 队伍ID ${teamId}`);
    try {
        // 更新匹配获胜者
        const match = tournamentData.matches.find(m => m.id === matchId);
        if (!match) {
            console.error(`未找到ID为${matchId}的比赛`);
            return;
        }
        match.winner = teamId;
        
        // 找到获胜球队的数据
        const team = tournamentData.teams.find(t => t.id === teamId);
        if (!team) {
            console.error(`未找到ID为${teamId}的队伍`);
            return;
        }
        
        // 更新下一轮（如果存在）
        updateNextRound(match);
        
        // 渲染视图更新
        renderTournament();
        
        // 保存预测数据
        savePredictions(false);
        
        console.log(`${team.name}晋级下一轮！`);
    } catch (error) {
        console.error("选择胜者时出错:", error);
    }
}

// 更新下一轮比赛
function updateNextRound(match) {
    console.log(`更新下一轮，比赛ID: ${match.id}, 胜者: ${match.winner}`);
    
    try {
        // 找到获胜的队伍
        const winnerTeam = match.winner === match.team1.id ? match.team1 : match.team2;
        if (!winnerTeam) {
            console.error('无法确定获胜队伍');
            return;
        }
        
        console.log(`确定的获胜队伍是: ${winnerTeam.name}`);
        
        // 确定下一轮比赛的ID和队伍位置
        let nextMatchId = null;
        let nextTeamPosition = null;
        
        // 根据当前比赛的轮次和位置确定下一轮的参数
        switch(match.round) {
            case 'quarterfinal':
                // 四分之一决赛 -> 半决赛
                if (match.position === 1) {
                    nextMatchId = 'semifinal1';
                    nextTeamPosition = 'team1';
                } else if (match.position === 2) {
                    nextMatchId = 'semifinal1';
                    nextTeamPosition = 'team2';
                } else if (match.position === 3) {
                    nextMatchId = 'semifinal2';
                    nextTeamPosition = 'team1';
                } else if (match.position === 4) {
                    nextMatchId = 'semifinal2';
                    nextTeamPosition = 'team2';
                }
                break;
            case 'semifinal':
                // 半决赛 -> 决赛
                if (match.position === 1) {
                    nextMatchId = 'final';
                    nextTeamPosition = 'team1';
                } else if (match.position === 2) {
                    nextMatchId = 'final';
                    nextTeamPosition = 'team2';
                }
                break;
            case 'final':
                // 决赛 -> 冠军
                tournamentData.champion = {...winnerTeam};
                console.log(`已更新冠军为: ${winnerTeam.name}`);
                renderChampion();
                return;
            default:
                console.error(`未知的比赛轮次: ${match.round}`);
                return;
        }
        
        // 如果有下一轮比赛，更新数据
        if (nextMatchId && nextTeamPosition) {
            const nextMatch = tournamentData.matches.find(m => m.id === nextMatchId);
            
            if (!nextMatch) {
                console.error(`未找到下一轮比赛，ID: ${nextMatchId}`);
                return;
            }
            
            console.log(`更新下一轮比赛${nextMatchId}的${nextTeamPosition}为${winnerTeam.name}`);
            nextMatch[nextTeamPosition] = {...winnerTeam};
            
            // 如果下一轮的双方都已经确定，清除胜者
            if (nextMatch.team1 && nextMatch.team1.name && nextMatch.team2 && nextMatch.team2.name) {
                nextMatch.winner = null;
                console.log(`下一轮比赛${nextMatchId}的双方已确定，清除了胜者`);
            }
        }
    } catch (error) {
        console.error('更新下一轮时出错:', error);
    }
}

// 渲染比赛
function renderMatches(containerId, matches) {
    const container = document.querySelector(`#${containerId} .matches`);
    if (!container) return;
    
    // 清空容器
    container.innerHTML = '';
    
    // 添加比赛
    matches.forEach(match => {
        const matchElement = createMatchElement(match);
        container.appendChild(matchElement);
    });
}

// 渲染决赛
function renderFinal() {
    const finalContainer = document.getElementById('final');
    finalContainer.innerHTML = '';
    
    // 添加决赛
    const finalMatch = tournamentData.matches.find(m => m.round === 'final');
    if (!finalMatch) {
        console.error('无法找到决赛数据');
        return;
    }
    
    // 创建决赛元素
    const finalElement = document.createElement('div');
    finalElement.className = 'final-match';
    finalElement.dataset.matchId = finalMatch.id;
    
    // 添加两支球队
    const team1Card = createTeamCard(finalMatch.team1);
    team1Card.dataset.matchId = finalMatch.id;
    team1Card.dataset.teamKey = 'team1';
    
    const team2Card = createTeamCard(finalMatch.team2);
    team2Card.dataset.matchId = finalMatch.id;
    team2Card.dataset.teamKey = 'team2';
    
    // 如果有胜者，标记选中状态
    if (finalMatch.winner) {
        if (finalMatch.winner === finalMatch.team1.id) {
            team1Card.classList.add('selected');
        } else if (finalMatch.winner === finalMatch.team2.id) {
            team2Card.classList.add('selected');
        }
    }
    
    // 为每个队伍卡片添加点击事件
    team1Card.addEventListener('click', function() {
        console.log(`点击了决赛队伍卡片: ${finalMatch.team1.name}, 比赛ID: ${finalMatch.id}`);
        selectWinner(finalMatch.id, finalMatch.team1.id);
    });
    
    team2Card.addEventListener('click', function() {
        console.log(`点击了决赛队伍卡片: ${finalMatch.team2.name}, 比赛ID: ${finalMatch.id}`);
        selectWinner(finalMatch.id, finalMatch.team2.id);
    });
    
    // 添加VS标志
    const vsDiv = document.createElement('div');
    vsDiv.className = 'vs';
    vsDiv.textContent = 'VS';
    
    // 组装决赛元素
    finalElement.appendChild(team1Card);
    finalElement.appendChild(vsDiv);
    finalElement.appendChild(team2Card);
    
    finalContainer.appendChild(finalElement);
    
    // 渲染冠军
    renderChampion();
}

// 渲染冠军
function renderChampion() {
    const championContainer = document.getElementById('champion');
    if (!championContainer) {
        console.error('找不到冠军容器元素');
        return;
    }
    
    // 清空容器
    championContainer.innerHTML = '';
    
    // 若没有冠军数据，则不显示
    if (!tournamentData.champion) {
        console.log('冠军数据不存在，不显示冠军');
        return;
    }
    
    // 创建冠军元素
    const championElement = document.createElement('div');
    championElement.className = 'champion-card';
    
    // 添加冠军队标
    const logoContainer = document.createElement('div');
    logoContainer.className = 'champion-logo';
    
    // 优先使用SVG图标
    if (tournamentData.champion.logo) {
        const logoImg = document.createElement('img');
        logoImg.src = tournamentData.champion.logo;
        logoImg.alt = tournamentData.champion.name;
        logoImg.style.maxWidth = '100%';
        logoImg.style.maxHeight = '100%';
        
        // 图片加载失败时创建文本logo
        logoImg.onerror = function() {
            console.log(`冠军图标加载失败: ${tournamentData.champion.logo}，使用文本替代`);
            logoContainer.innerHTML = '';
            logoContainer.appendChild(createTextLogo(tournamentData.champion));
        };
        
        logoContainer.appendChild(logoImg);
    } else {
        // 如果没有logo路径，使用文本logo
        logoContainer.appendChild(createTextLogo(tournamentData.champion));
    }
    
    // 添加冠军队名
    const nameElement = document.createElement('div');
    nameElement.className = 'champion-name';
    nameElement.textContent = tournamentData.champion.name;
    
    // 添加冠军标题
    const titleElement = document.createElement('div');
    titleElement.className = 'champion-title';
    titleElement.textContent = '冠军';
    
    // 组装冠军元素
    championElement.appendChild(titleElement);
    championElement.appendChild(logoContainer);
    championElement.appendChild(nameElement);
    
    championContainer.appendChild(championElement);
    
    console.log(`已渲染冠军: ${tournamentData.champion.name}`);
}

// 检查图片是否存在，如果不存在则使用备用图片
function checkImage(path, fallbackPath) {
    const img = new Image();
    img.src = path;
    img.onerror = function() {
        this.src = fallbackPath;
    };
    return img.src;
}

// 渲染整个赛事结构
function renderTournament() {
    console.log('渲染整个赛事结构');
    
    try {
        // 渲染四分之一决赛
        const quarterfinalsLeftMatches = tournamentData.matches.filter(m => m.round === 'quarterfinal' && m.position <= 2);
        const quarterfinalsRightMatches = tournamentData.matches.filter(m => m.round === 'quarterfinal' && m.position > 2);
        
        renderMatches('quarterfinals-left', quarterfinalsLeftMatches);
        renderMatches('quarterfinals-right', quarterfinalsRightMatches);
        
        // 渲染半决赛
        const semifinalsLeftMatches = tournamentData.matches.filter(m => m.round === 'semifinal' && m.position === 1);
        const semifinalsRightMatches = tournamentData.matches.filter(m => m.round === 'semifinal' && m.position === 2);
        
        renderMatches('semifinals-left', semifinalsLeftMatches);
        renderMatches('semifinals-right', semifinalsRightMatches);
        
        // 渲染决赛
        renderFinal();
        
        // 渲染冠军
        renderChampion();
        
        console.log('赛事结构渲染完成');
    } catch (error) {
        console.error('渲染赛事结构时出错:', error);
    }
}

// 添加自定义队伍功能
function addCustomTeam() {
    // 打开模态框
    const modal = document.getElementById('add-team-modal');
    modal.style.display = 'block';
}

// 关闭模态框
function closeModal() {
    const modal = document.getElementById('add-team-modal');
    modal.style.display = 'none';
}

// 保存自定义队伍
function saveCustomTeam() {
    const teamName = document.getElementById('team-name-input').value.trim();
    const teamColor = document.getElementById('team-color-input').value;
    const teamLogo = document.getElementById('team-logo-input').value.trim();
    
    if (!teamName) {
        alert('请输入队伍名称');
        return;
    }
    
    // 创建新队伍
    const newTeam = {
        id: 'custom' + (tournamentData.teams.length + 1),
        name: teamName,
        logo: teamLogo,
        color: teamColor
    };
    
    // 添加到队伍列表
    tournamentData.teams.push(newTeam);
    
    // 添加颜色映射
    teamColors[teamName] = teamColor;
    
    // 更新队伍选择下拉菜单
    updateTeamSelectors();
    
    // 关闭模态框
    closeModal();
    
    // 清空输入
    document.getElementById('team-name-input').value = '';
    document.getElementById('team-logo-input').value = '';
    document.getElementById('team-color-input').value = '#CCCCCC';
    
    // 保存数据
    savePredictions(false);
    
    // 显示通知
    showNotification(`成功添加队伍: ${teamName}`);
}

// 更新队伍选择下拉菜单
function updateTeamSelectors() {
    const selectors = document.querySelectorAll('.team-selector');
    
    selectors.forEach(selector => {
        // 保存当前选择的值
        const currentValue = selector.value;
        
        // 清空选项
        selector.innerHTML = '<option value="">请选择队伍</option>';
        
        // 添加队伍选项
        tournamentData.teams.forEach(team => {
            const option = document.createElement('option');
            option.value = team.id;
            option.textContent = team.name;
            selector.appendChild(option);
        });
        
        // 恢复选择的值
        if (currentValue) {
            selector.value = currentValue;
        }
    });
}

// 应用选择的队伍到比赛
function applyTeamSelection() {
    // 获取所有队伍选择器
    const selectors = document.querySelectorAll('.team-selector');
    
    // 检查是否所有的选择器都有选择值
    let allSelected = true;
    selectors.forEach(selector => {
        if (!selector.value) {
            allSelected = false;
        }
    });
    
    if (!allSelected) {
        alert('请选择所有队伍');
        return;
    }
    
    // 获取所有队伍选择的值
    const selectedTeams = [];
    selectors.forEach(selector => {
        const teamId = selector.value;
        const team = tournamentData.teams.find(t => t.id === teamId);
        if (team) {
            selectedTeams.push(JSON.parse(JSON.stringify(team)));
        }
    });
    
    // 应用到四分之一决赛
    const quarterFinals = tournamentData.matches.filter(m => m.round === 'quarterfinal');
    for (let i = 0; i < quarterFinals.length; i++) {
        quarterFinals[i].team1 = selectedTeams[i * 2];
        quarterFinals[i].team2 = selectedTeams[i * 2 + 1];
        quarterFinals[i].winner = null;
    }
    
    // 重置半决赛和决赛
    tournamentData.matches.forEach(match => {
        if (match.round === 'semifinal' || match.round === 'final') {
            match.team1 = { id: 'placeholder' + (Math.random().toString(36).substring(2, 7)), name: '待定', logo: '' };
            match.team2 = { id: 'placeholder' + (Math.random().toString(36).substring(2, 7)), name: '待定', logo: '' };
            match.winner = null;
        }
    });
    
    // 重置冠军
    tournamentData.champion = null;
    
    // 保存数据
    savePredictions(false);
    
    // 重新渲染
    renderTournament();
    
    // 显示通知
    showNotification('队伍设置已应用');
}

// 创建用户界面元素
function createUserInterface() {
    // 创建添加队伍模态框
    const modalHtml = `
        <div id="add-team-modal" class="modal">
            <div class="modal-content">
                <div class="modal-header">
                    <h2>添加自定义队伍</h2>
                    <span id="close-modal-btn" class="close">&times;</span>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="team-name-input">队伍名称:</label>
                        <input type="text" id="team-name-input" placeholder="例如: 巴萨">
                    </div>
                    <div class="form-group">
                        <label for="team-color-input">队伍颜色:</label>
                        <input type="color" id="team-color-input" value="#CCCCCC">
                    </div>
                    <div class="form-group">
                        <label for="team-logo-input">徽标URL (可选):</label>
                        <input type="text" id="team-logo-input" placeholder="例如: images/team-logo.svg">
                        <small>如果留空，将使用文字徽标</small>
                    </div>
                    <button id="save-team-btn" class="btn">保存队伍</button>
                </div>
            </div>
        </div>
    `;
    
    // 创建队伍选择面板
    const teamSelectorHtml = `
        <div id="team-selector-panel" class="panel">
            <h3>选择参赛队伍</h3>
            <div class="team-selector-container">
                <div class="team-selector-group">
                    <label>四分之一决赛 1:</label>
                    <select class="team-selector" data-position="qf1-team1"></select>
                    <span>vs</span>
                    <select class="team-selector" data-position="qf1-team2"></select>
                </div>
                <div class="team-selector-group">
                    <label>四分之一决赛 2:</label>
                    <select class="team-selector" data-position="qf2-team1"></select>
                    <span>vs</span>
                    <select class="team-selector" data-position="qf2-team2"></select>
                </div>
                <div class="team-selector-group">
                    <label>四分之一决赛 3:</label>
                    <select class="team-selector" data-position="qf3-team1"></select>
                    <span>vs</span>
                    <select class="team-selector" data-position="qf3-team2"></select>
                </div>
                <div class="team-selector-group">
                    <label>四分之一决赛 4:</label>
                    <select class="team-selector" data-position="qf4-team1"></select>
                    <span>vs</span>
                    <select class="team-selector" data-position="qf4-team2"></select>
                </div>
                <div class="buttons-container">
                    <button id="addCustomTeam" class="btn">添加自定义队伍</button>
                    <button id="apply-teams-btn" class="btn btn-primary">应用队伍选择</button>
                </div>
            </div>
        </div>
    `;
    
    // 添加到DOM
    const container = document.getElementById('tournament-container');
    if (container) {
        // 添加队伍选择面板
        const teamSelectorContainer = document.createElement('div');
        teamSelectorContainer.innerHTML = teamSelectorHtml;
        container.insertBefore(teamSelectorContainer, container.firstChild);
        
        // 添加模态框
        const modalContainer = document.createElement('div');
        modalContainer.innerHTML = modalHtml;
        document.body.appendChild(modalContainer);
        
        // 添加样式
        const style = document.createElement('style');
        style.textContent = `
            .modal {
                display: none;
                position: fixed;
                z-index: 1000;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(0,0,0,0.5);
            }
            .modal-content {
                background-color: #fff;
                margin: 10% auto;
                padding: 20px;
                border-radius: 5px;
                width: 50%;
                max-width: 500px;
                box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            }
            .modal-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                border-bottom: 1px solid #ddd;
                padding-bottom: 10px;
                margin-bottom: 15px;
            }
            .close {
                color: #aaa;
                font-size: 28px;
                font-weight: bold;
                cursor: pointer;
            }
            .close:hover {
                color: #000;
            }
            .form-group {
                margin-bottom: 15px;
            }
            .form-group label {
                display: block;
                margin-bottom: 5px;
                font-weight: bold;
            }
            .form-group input {
                width: 100%;
                padding: 8px;
                border: 1px solid #ddd;
                border-radius: 4px;
                box-sizing: border-box;
            }
            .btn {
                padding: 8px 15px;
                border: none;
                border-radius: 4px;
                background-color: #ddd;
                cursor: pointer;
                font-size: 14px;
            }
            .btn:hover {
                background-color: #ccc;
            }
            .btn-primary {
                background-color: #4a90e2;
                color: white;
            }
            .btn-primary:hover {
                background-color: #3a80d2;
            }
            .panel {
                background-color: #f9f9f9;
                border-radius: 5px;
                padding: 15px;
                margin-bottom: 20px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            .team-selector-container {
                display: flex;
                flex-direction: column;
                gap: 10px;
            }
            .team-selector-group {
                display: flex;
                align-items: center;
                gap: 10px;
            }
            .team-selector {
                flex: 1;
                padding: 8px;
                border: 1px solid #ddd;
                border-radius: 4px;
            }
            .buttons-container {
                display: flex;
                justify-content: space-between;
                margin-top: 15px;
            }
        `;
        document.head.appendChild(style);
    }
}

// 保存为图片功能
function saveAsImage() {
    console.log('开始执行保存为图片功能...');
    showNotification('正在生成图片，请稍候...');
    
    try {
        // 确认HTML2Canvas是否可用
        if (typeof html2canvas === 'undefined') {
            console.error('HTML2Canvas库未加载！');
            showNotification('图片生成失败：HTML2Canvas库未加载');
            return;
        }
        
        // 先隐藏控制按钮和队伍选择面板
        const controls = document.querySelector('.controls');
        if (!controls) {
            console.error('未找到控制按钮容器！');
            showNotification('图片生成失败：DOM元素未找到');
            return;
        }
        
        const teamSelector = document.getElementById('team-selector-panel');
        
        // 保存原始显示状态
        const controlsDisplay = controls.style.display;
        const teamSelectorDisplay = teamSelector ? teamSelector.style.display : 'block';
        
        // 获取要截图的元素
        const bracket = document.querySelector('.tournament-bracket');
        if (!bracket) {
            console.error('未找到比赛对阵图元素！');
            showNotification('图片生成失败：比赛对阵图未找到');
            return;
        }
        
        console.log('已找到所有必要的DOM元素');
        
        // 临时隐藏元素
        controls.style.display = 'none';
        if (teamSelector) teamSelector.style.display = 'none';
        
        // 添加水印
        let watermark = document.createElement('div');
        watermark.className = 'watermark';
        watermark.innerHTML = `
            <p>欧冠预测工具 - ${new Date().toISOString().slice(0, 10)}</p>
        `;
        watermark.style.position = 'absolute';
        watermark.style.bottom = '10px';
        watermark.style.right = '10px';
        watermark.style.color = '#999';
        watermark.style.fontSize = '12px';
        watermark.style.opacity = '0.7';
        
        // 添加水印到页面
        bracket.appendChild(watermark);
        
        // 临时存储和替换所有队徽图片，防止跨域问题
        console.log('临时替换图片元素以避免跨域污染...');
        const allTeamLogos = bracket.querySelectorAll('.team-logo');
        const originalContents = [];
        
        // 先保存原始内容，再替换为纯文本logo
        allTeamLogos.forEach(logoContainer => {
            // 保存原始内容
            originalContents.push({
                element: logoContainer,
                content: logoContainer.innerHTML
            });
            
            // 获取队伍名称
            const teamCard = logoContainer.closest('.team-card');
            let teamName = '队伍';
            if (teamCard) {
                const nameElement = teamCard.querySelector('.team-name');
                if (nameElement) {
                    teamName = nameElement.textContent || '队伍';
                }
            }
            
            // 创建纯文本logo
            const textLogo = document.createElement('div');
            textLogo.className = 'text-logo';
            
            // 查找队伍颜色
            let color = teamColors[teamName] || teamColors['默认'];
            
            // 设置样式
            textLogo.style.backgroundColor = color;
            textLogo.style.color = isLightColor(color) ? '#000000' : '#FFFFFF';
            textLogo.style.width = '36px';
            textLogo.style.height = '36px';
            textLogo.style.display = 'flex';
            textLogo.style.alignItems = 'center';
            textLogo.style.justifyContent = 'center';
            textLogo.style.borderRadius = '50%';
            textLogo.style.fontWeight = 'bold';
            textLogo.style.margin = '0 auto';
            
            // 显示队伍名称的首字母或首个汉字
            textLogo.textContent = teamName.charAt(0);
            
            // 替换原始内容
            logoContainer.innerHTML = '';
            logoContainer.appendChild(textLogo);
        });
        
        // 同样处理冠军logo（如果存在）
        const championLogo = bracket.querySelector('.champion-logo');
        let originalChampionContent = null;
        if (championLogo) {
            originalChampionContent = {
                element: championLogo,
                content: championLogo.innerHTML
            };
            
            // 获取冠军队名
            const championName = bracket.querySelector('.champion-name')?.textContent || '冠军';
            
            // 创建纯文本logo
            const textLogo = document.createElement('div');
            textLogo.className = 'text-logo';
            
            // 设置样式
            let color = teamColors[championName] || teamColors['默认'];
            textLogo.style.backgroundColor = color;
            textLogo.style.color = isLightColor(color) ? '#000000' : '#FFFFFF';
            textLogo.style.width = '60px';
            textLogo.style.height = '60px';
            textLogo.style.display = 'flex';
            textLogo.style.alignItems = 'center';
            textLogo.style.justifyContent = 'center';
            textLogo.style.borderRadius = '50%';
            textLogo.style.fontWeight = 'bold';
            textLogo.style.margin = '0 auto';
            
            // 显示队伍名称的首字母或首个汉字
            textLogo.textContent = championName.charAt(0);
            
            // 替换原始内容
            championLogo.innerHTML = '';
            championLogo.appendChild(textLogo);
        }
        
        console.log('开始调用HTML2Canvas生成图片...');
        
        // 使用html2canvas生成图片
        html2canvas(bracket, {
            backgroundColor: '#f0f2f5',
            scale: 2, // 提高图片清晰度
            logging: true, // 启用日志
            allowTaint: false,  // 不允许污染画布
            useCORS: false,     // 不使用CORS，避免跨域问题
            foreignObjectRendering: false // 关闭foreignObject渲染，提高兼容性
        }).then(canvas => {
            console.log('HTML2Canvas成功生成图片！');
            
            // 移除水印
            bracket.removeChild(watermark);
            
            // 恢复队徽图片
            originalContents.forEach(item => {
                item.element.innerHTML = item.content;
            });
            
            // 恢复冠军logo
            if (originalChampionContent) {
                originalChampionContent.element.innerHTML = originalChampionContent.content;
            }
            
            // 恢复原始显示状态
            controls.style.display = controlsDisplay;
            if (teamSelector) teamSelector.style.display = teamSelectorDisplay;
            
            // 显示分享按钮
            const shareButtons = document.querySelector('.share-buttons');
            if (shareButtons) {
                shareButtons.style.display = 'block';
            } else {
                console.warn('未找到分享按钮容器');
            }
            
            try {
                // 保存canvas内容为图片
                const imageData = canvas.toDataURL('image/png');
                console.log('生成的图片大小约为: ' + Math.round(imageData.length / 1024) + 'KB');
                
                // 创建一个链接来下载图片
                const link = document.createElement('a');
                link.href = imageData;
                link.download = `欧冠预测_${new Date().toISOString().slice(0, 10)}.png`;
                
                // 将图片数据保存到sessionStorage，以便分享模态框使用
                try {
                    sessionStorage.setItem('predictionImage', imageData);
                    console.log('图片数据已保存到sessionStorage');
                } catch (err) {
                    console.error('保存图片到sessionStorage失败: ', err);
                }
                
                // 触发下载
                document.body.appendChild(link);
                console.log('准备触发下载...');
                link.click();
                document.body.removeChild(link);
                
                showNotification('图片已保存！现在您可以选择分享到社交媒体');
            } catch (error) {
                console.error('导出图片数据失败:', error);
                showNotification('图片生成失败：' + error.message);
            }
            
            console.log('保存为图片功能执行完成');
        }).catch(error => {
            console.error('HTML2Canvas生成图片失败: ', error);
            showNotification('图片生成失败，请查看控制台了解详情');
            
            // 恢复队徽图片
            originalContents.forEach(item => {
                item.element.innerHTML = item.content;
            });
            
            // 恢复冠军logo
            if (originalChampionContent) {
                originalChampionContent.element.innerHTML = originalChampionContent.content;
            }
            
            // 移除水印并恢复元素显示
            if (bracket.contains(watermark)) {
                bracket.removeChild(watermark);
            }
            controls.style.display = controlsDisplay;
            if (teamSelector) teamSelector.style.display = teamSelectorDisplay;
        });
    } catch (error) {
        console.error('生成图片时出错:', error);
        showNotification('图片生成失败，请稍后再试');
        
        // 确保恢复控制按钮和队伍选择面板的显示
        const controls = document.querySelector('.controls');
        const teamSelector = document.getElementById('team-selector-panel');
        
        if (controls) controls.style.display = 'block';
        if (teamSelector) teamSelector.style.display = 'block';
    }
}

// 处理分享到社交媒体的功能
function handleShare(platform) {
    // 获取保存的图片数据
    const imageData = sessionStorage.getItem('predictionImage');
    if (!imageData) {
        showNotification('请先生成图片');
        return;
    }
    
    // 打开分享模态框
    const shareModal = document.getElementById('share-modal');
    const shareImageContainer = document.getElementById('share-image-container');
    
    // 清空容器并添加图片
    shareImageContainer.innerHTML = '';
    const img = new Image();
    img.src = imageData;
    img.style.maxWidth = '100%';
    shareImageContainer.appendChild(img);
    
    // 显示模态框
    shareModal.style.display = 'block';
    
    // 记录选择的平台
    sessionStorage.setItem('selectedPlatform', platform);
}

// 取消分享
function cancelShare() {
    const shareButtons = document.querySelector('.share-buttons');
    shareButtons.style.display = 'none';
}

// 关闭分享模态框
function closeShareModal() {
    const shareModal = document.getElementById('share-modal');
    shareModal.style.display = 'none';
}

// 下载分享图片
function downloadShareImage() {
    const imageData = sessionStorage.getItem('predictionImage');
    if (imageData) {
        const link = document.createElement('a');
        link.href = imageData;
        link.download = `欧冠预测_${new Date().toISOString().slice(0, 10)}.png`;
        link.click();
        showNotification('图片已下载，请按照说明分享到社交媒体');
    } else {
        showNotification('没有可用的图片');
    }
}

// 添加文件操作相关变量
const DEFAULT_PREDICTION_FILE = 'data/champions_prediction.json';
let currentFileName = DEFAULT_PREDICTION_FILE;

// 将预测数据保存为JSON文件
function savePredictionToFile(customFileName = null, showNotificationFlag = true) {
    // 获取当前预测数据
    const predictionData = getFullPredictionData();
    
    // 使用默认文件名或自定义文件名
    const fileName = customFileName || currentFileName;
    
    // 创建JSON字符串
    const dataStr = JSON.stringify(predictionData, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(dataBlob);
    
    const downloadLink = document.createElement('a');
    downloadLink.href = url;
    
    // 如果是保存到data目录，确保文件名正确
    if (fileName === DEFAULT_PREDICTION_FILE) {
        // 直接使用champions_prediction.json作为文件名
        downloadLink.download = 'champions_prediction.json';
    } else {
        // 其他情况提取文件名或使用时间戳文件名
        const displayName = fileName.includes('/') ? fileName.split('/').pop() : fileName;
        downloadLink.download = displayName || `预测_${new Date().toISOString().slice(0, 10)}.json`;
    }
    
    // 触发下载
    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
    
    // 如果是自定义文件名，更新当前文件名
    if (customFileName) {
        currentFileName = customFileName;
    }
    
    // 同时保存到localStorage作为备份
    localStorage.setItem('lastPrediction', dataStr);
    
    // 显示成功提示，根据文件名选择不同消息
    if (showNotificationFlag) {
        if (fileName === DEFAULT_PREDICTION_FILE) {
            showNotification(`预测已保存为champions_prediction.json，请手动放入data目录`);
        } else {
            showNotification(`预测已下载为: ${downloadLink.download}`);
        }
    }
}

// 添加自定义文件名保存功能
function saveWithCustomName() {
    // 直接使用默认文件名保存，并且不显示提示
    savePredictionToFile(DEFAULT_PREDICTION_FILE, false);
}

// 读取JSON预测文件
function loadPredictionFromFile(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        
        reader.onload = (event) => {
            try {
                const data = JSON.parse(event.target.result);
                resolve(data);
            } catch (err) {
                reject(new Error('文件格式错误，无法解析JSON数据'));
            }
        };
        
        reader.onerror = () => reject(new Error('读取文件时出错'));
        reader.readAsText(file);
    });
}

// 处理文件选择并加载
function handleFileSelect(event) {
    const file = event.target.files[0];
    if (!file) return;
    
    // 更新当前文件名
    currentFileName = file.name;
    
    loadPredictionFromFile(file)
        .then((data) => {
            // 加载预测数据到应用
            loadPredictionData(data);
        })
        .catch((error) => {
            console.error('加载文件失败:', error);
            showNotification(`加载文件失败: ${error.message}`, 'error');
        });
}

// 创建文件选择器
function createFileSelector() {
    const fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.accept = '.json';
    fileInput.style.display = 'none';
    fileInput.addEventListener('change', handleFileSelect);
    document.body.appendChild(fileInput);
    return fileInput;
}

// 初始化加载默认文件（如果存在）
function tryLoadDefaultFile() {
    console.log('初始化应用默认状态');
    
    // 从服务器加载默认预测文件
    fetch(DEFAULT_PREDICTION_FILE)
        .then(response => {
            if (!response.ok) {
                throw new Error('无法加载默认预测文件');
            }
            return response.json();
        })
        .then(data => {
            console.log('从服务器加载默认预测文件成功');
            loadPredictionData(data);
        })
        .catch(err => {
            console.log('未找到默认预测文件或加载失败，尝试从localStorage加载', err);
            
            // 如果服务器文件不存在，尝试从localStorage加载
            const savedData = localStorage.getItem('lastPrediction');
            if (savedData) {
                try {
                    console.log('从localStorage加载保存的预测数据');
                    const data = JSON.parse(savedData);
                    loadPredictionData(data);
                } catch (e) {
                    console.error('解析本地存储数据失败', e);
                }
            } else {
                console.log('使用初始状态，没有找到可用的预测数据');
            }
        });
}

// 获取完整预测数据
function getFullPredictionData() {
    return {
        teams: tournamentData.teams,
        matches: tournamentData.matches,
        champion: tournamentData.champion
    };
}

// 加载预测数据到应用
function loadPredictionData(data) {
    if (!data || !data.matches) {
        console.error('无效的预测数据格式');
        showNotification('无效的预测数据格式', 'error');
        return;
    }
    
    // 重置现有数据
    resetPredictions(false);
    
    // 应用新数据
    if (data.teams && Array.isArray(data.teams)) {
        tournamentData.teams = data.teams;
    }
    
    if (data.matches && Array.isArray(data.matches)) {
        // 更新比赛数据
        tournamentData.matches = data.matches;
    }
    
    if (data.champion) {
        tournamentData.champion = data.champion;
    }
    
    // 重新渲染界面
    renderTournament();
    
    // 更新队伍选择器
    updateTeamSelectors();
    
    console.log('已加载预测数据:', data);
}

// 初始化文件功能
function initializeFileFeatures() {
    // 添加UI控件
    addFileControls();
    
    // 尝试加载默认文件
    tryLoadDefaultFile();
}

// 初始化应用程序
function initApp() {
    console.log('正在初始化应用...');
    
    try {
        // 清除图片缓存
        clearImageCache();
        
        // 从teams对象初始化tournamentData.teams
        tournamentData.teams = [];
        
        // 合并左侧和右侧的球队
        const allTeams = [...teams.left, ...teams.right];
        
        // 添加到tournamentData
        allTeams.forEach(team => {
            tournamentData.teams.push({
                id: team.id,
                name: team.name,
                logo: team.logo
            });
        });
        
        console.log('已从teams对象加载队伍数据');
        
        // 初始化四分之一决赛队伍
        const quarterFinals = tournamentData.matches.filter(m => m.round === 'quarterfinal');
        for (let i = 0; i < 4; i++) {
            if (i < 2) { // 左侧两场比赛
                quarterFinals[i].team1 = { 
                    id: teams.left[i*2].id, 
                    name: teams.left[i*2].name, 
                    logo: teams.left[i*2].logo 
                };
                quarterFinals[i].team2 = { 
                    id: teams.left[i*2+1].id, 
                    name: teams.left[i*2+1].name, 
                    logo: teams.left[i*2+1].logo 
                };
            } else { // 右侧两场比赛
                const rightIdx = i - 2;
                quarterFinals[i].team1 = { 
                    id: teams.right[rightIdx*2].id, 
                    name: teams.right[rightIdx*2].name, 
                    logo: teams.right[rightIdx*2].logo 
                };
                quarterFinals[i].team2 = { 
                    id: teams.right[rightIdx*2+1].id, 
                    name: teams.right[rightIdx*2+1].name, 
                    logo: teams.right[rightIdx*2+1].logo 
                };
            }
        }
        
        // 创建用户界面元素
        createUserInterface();
        
        // 渲染赛事结构
        renderTournament();
        
        // 更新队伍选择下拉菜单
        updateTeamSelectors();
        
        // 添加事件监听器
        document.getElementById('savePredictions').addEventListener('click', () => savePredictions(true));
        document.getElementById('resetPredictions').addEventListener('click', resetPredictions);
        document.getElementById('exportPredictions').addEventListener('click', exportPredictions);
        document.getElementById('addCustomTeam').addEventListener('click', addCustomTeam);
        document.getElementById('save-team-btn').addEventListener('click', saveCustomTeam);
        document.getElementById('close-modal-btn').addEventListener('click', closeModal);
        document.getElementById('apply-teams-btn').addEventListener('click', applyTeamSelection);
        
        // 添加保存为图片和分享功能的事件监听器
        document.getElementById('saveAsImage').addEventListener('click', saveAsImage);
        document.getElementById('shareToWeChat').addEventListener('click', () => handleShare('wechat'));
        document.getElementById('shareToWeibo').addEventListener('click', () => handleShare('weibo'));
        document.getElementById('shareToBilibili').addEventListener('click', () => handleShare('bilibili'));
        document.getElementById('cancelShare').addEventListener('click', cancelShare);
        
        // 分享模态框相关事件监听器
        document.getElementById('close-share-modal').addEventListener('click', closeShareModal);
        document.getElementById('download-share-image').addEventListener('click', downloadShareImage);
        
        // 初始化文件功能
        initializeFileFeatures();
        
        console.log('应用初始化完成！');
        showNotification('欧冠预测工具已加载完成！');
    } catch (error) {
        console.error('初始化应用程序时出错:', error);
    }
}

// 当文档加载完成后初始化应用
document.addEventListener('DOMContentLoaded', initApp);

// 清除图片缓存
function clearImageCache() {
    console.log('正在清除图片缓存...');
    try {
        const images = document.querySelectorAll('img');
        images.forEach(img => {
            // 添加随机参数到URL以绕过缓存
            if (img.src) {
                const randomParam = `?v=${Math.random().toString(36).substring(2, 15)}`;
                img.src = img.src.split('?')[0] + randomParam;
            }
        });
        console.log('图片缓存已清除');
    } catch (error) {
        console.error('清除图片缓存时出错:', error);
    }
}

// 添加UI组件
function addFileControls() {
    const controlsContainer = document.querySelector('.controls') || document.getElementById('controls');
    if (!controlsContainer) {
        console.error('无法找到控制按钮容器');
        return;
    }
    
    // 添加加载文件按钮
    const loadButton = document.createElement('button');
    loadButton.id = 'load-prediction';
    loadButton.className = 'control-button';
    loadButton.innerHTML = '读取预测文件';
    
    // 添加保存文件按钮
    const saveButton = document.createElement('button');
    saveButton.id = 'save-prediction';
    saveButton.className = 'control-button';
    saveButton.innerHTML = '下载预测文件';
    
    // 添加自定义文件名保存按钮
    const saveAsButton = document.createElement('button');
    saveAsButton.id = 'save-prediction-as';
    saveAsButton.className = 'control-button';
    saveAsButton.innerHTML = '保存到data目录/';
    
    // 创建隐藏的文件选择器
    const fileSelector = createFileSelector();
    
    // 添加事件监听器
    loadButton.addEventListener('click', function() {
        // 提供从服务器加载或从本地文件选择的选项
        const loadFromServer = confirm('是否从服务器加载默认预测文件？\n\n点击"确定"从服务器加载\n点击"取消"选择本地文件');
        
        if (loadFromServer) {
            // 从服务器加载
            fetch(DEFAULT_PREDICTION_FILE)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('无法加载默认预测文件，请检查文件是否存在');
                    }
                    return response.json();
                })
                .then(data => {
                    loadPredictionData(data);
                    showNotification('成功从服务器加载预测文件');
                })
                .catch(err => {
                    console.error('加载服务器文件失败:', err);
                    showNotification('加载服务器文件失败: ' + err.message, 'error');
                });
        } else {
            // 从本地文件选择
            fileSelector.click();
        }
    });
    
    saveButton.addEventListener('click', () => savePredictionToFile());
    saveAsButton.addEventListener('click', saveWithCustomName);
    
    // 添加到控制容器
    controlsContainer.appendChild(loadButton);
    controlsContainer.appendChild(saveButton);
    controlsContainer.appendChild(saveAsButton);
} 